package com.jdbc.dao;

import com.jdbc.pojo.Account;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public class AccountDaoImpl implements AccountDao {
@Autowired
    private JdbcTemplate jdbcTemplate;

    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    @Override
    public int addAccount(Account account) {
        //准备要执行的sql语句
        String sql="insert account(username,balance) values(?,?)";

        //准备参数:update方法的第二个参数应该是一个参数数组。参数数组数据的位置要与sql语句中？代表的字段相对应
        Object params[] =new Object[]{account.getUsername(),account.getBalance()};

        //调用update方法执行sql语句
        int n= jdbcTemplate.update(sql,params);
        return n;
    }

    @Override
    public int updateAccountById(Account account) {
        String sql="update account set username=?,balance=? where id=?";
        Object params[] =new Object[]{account.getUsername(),account.getBalance(),account.getId()};
        int n= jdbcTemplate.update(sql,params);
        return n;

    }

    @Override
    public int updateBalanceById(int id, double balance) {
        String sql="update account set balance=? where id=?";
        Object params[] =new Object[]{balance,id};
        int n= jdbcTemplate.update(sql,params);
        return n;
    }

    @Override
    public int deleteAccountById(int id) {
        String sql="delete from account where id=?";
        int n = jdbcTemplate.update(sql, id);
        return n;
    }

    @Override
    public Account findById(int id) {
        String sql="select * from account where id=?";
        RowMapper<Account> rowMapper=new BeanPropertyRowMapper<>(Account.class);
        Account account=null;
        try{
            account=jdbcTemplate.queryForObject(sql,rowMapper,id);
        }catch (Exception e){

        }
        return account;
    }

    @Override
    public List<Account> findAll() {
        String sql="select * from account";
        RowMapper<Account> rowMapper=new BeanPropertyRowMapper<>(Account.class);
        List<Account> accounts = jdbcTemplate.query(sql, rowMapper);
        return accounts;
    }
}
